using System;
using System.Data;
using System.Configuration;
using System.Web.UI.WebControls;
using System.IO;
using Microsoft.Health.Samples.PatientConnect.TreyResearch.HealthVaultAdapter;
using System.Collections.ObjectModel;
using Microsoft.Health;
using Microsoft.Health.ItemTypes;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Text;

public partial class ProviderRegistration : System.Web.UI.Page
{
    private const string _CcrTypeId = "1e1ccbfc-a55d-4d91-8940-fa2fbf73c195";
    private const string _CcdTypeId = "9c48a2b8-952c-4f5a-935d-f3292326bf54";
    private const string _BasicDemographicTypeId = "bf516a61-5252-4c28-a979-27f45f62f78d";


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Practice providerPractice = new Practice(Path.Combine(Server.MapPath(@"Data"), Constants.PracticeXmlFileName));
            ReadHealthVaultItemTypes inbound = new ReadHealthVaultItemTypes(new Guid(ConfigurationManager.AppSettings["ApplicationId"]));
            Collection<HealthVaultThingTypes> thingTypeCollection = inbound.GetAllThingType;

            GridView1.DataSource = PopulateThingTypeTable(thingTypeCollection);
            GridView1.DataBind();
        }
    }

    /// <summary>
    /// Create thing type table
    /// </summary>
    /// <returns>DataTable</returns>
    private DataTable CreateThingTypeTable()
    {
        DataTable thingTypeTable = new DataTable();
        thingTypeTable.Columns.Add("Item");
        thingTypeTable.Columns.Add("Create", typeof(bool));
        thingTypeTable.Columns.Add("Read", typeof(bool));
        thingTypeTable.Columns.Add("Update", typeof(bool));
        thingTypeTable.Columns.Add("Delete", typeof(bool));
        thingTypeTable.Columns.Add("TypeId");
        return thingTypeTable;
    }

    /// <summary>
    /// Populate thing type table and bind to Grid view
    /// </summary>
    /// <param name="thingTypeCollection">thing type collection</param>
    private DataView PopulateThingTypeTable(Collection<HealthVaultThingTypes> thingTypeCollection)
    {
        DataTable thingTypeTable = CreateThingTypeTable();
        for (int iterator = 0; iterator < thingTypeCollection.Count; iterator++)
        {
            object[] parameters = new object[6];
            parameters[0] = thingTypeCollection[iterator].ItemName;
            parameters[5] = thingTypeCollection[iterator].TypeId;
            if ((parameters[5].ToString().Equals(Medication.TypeId.ToString()) ||
           parameters[5].ToString().Equals(LabTestResults.TypeId.ToString()) ||
           parameters[5].ToString().Equals(Basic.TypeId.ToString()) ||
           parameters[5].ToString().Equals(PersonalImage.TypeId.ToString()) ||
           parameters[5].ToString().Equals(_BasicDemographicTypeId)) ||
           parameters[5].ToString().Equals(_CcdTypeId) ||
           parameters[5].ToString().Equals(_CcrTypeId))
            {
                parameters[1] = Convert.ToBoolean("true");
            }
            else
            {
                parameters[1] = Convert.ToBoolean("false");
            }
            parameters[2] = Convert.ToBoolean("false");
            parameters[3] = Convert.ToBoolean("false");
            parameters[4] = Convert.ToBoolean("false");
            thingTypeTable.Rows.Add(parameters);
        }
        DataView dataViewThingType = new DataView(thingTypeTable);
        dataViewThingType.Sort = "Create desc";
        return dataViewThingType;
    }



    private ApplicationInfo CreateApplicationInfo()
    {
        ApplicationInfo appinfo = new ApplicationInfo();
        DataTable authTable = new DataTable();
        X509Certificate cert = new X509Certificate(Server.MapPath("Master One_ID-1fbc292c-30be-4dc1-b870-606878e91d03.p12"));
        appinfo.PublicKeys.Add(cert.GetRawCertData()); //Add certificate public key

        //Create authorization table
        authTable = CreateAuthorizationTable();

        //Populate OfflineBaseAuthorizations
        foreach (AuthorizationRule authrule in PatientConnectUtilities.SetAuthorizationRule(authTable))
        {
            appinfo.OfflineBaseAuthorizations.Add(authrule);
        }

        // Additional detail information for application settings
        if (!string.IsNullOrEmpty(TextBoxActionURL.Text))
        {
            appinfo.ActionUrl = new Uri(TextBoxActionURL.Text);
        }
        appinfo.Name = TextBoxProviderName.Text.Trim();
        appinfo.AuthorizationReason = TextBoxAuthorizationReason.Text.Trim();
        appinfo.Description = TextBoxProviderDescription.Text.Trim();
        appinfo.DomainName = "contoso.com";
        appinfo.LargeLogo = new ApplicationBinaryConfiguration(FileUploadLogo.FileContent, "Image");
        appinfo.PrivacyStatement = new ApplicationBinaryConfiguration(new MemoryStream(UTF8Encoding.Default.GetBytes(TextBoxPrivacyStatement.Text.Trim())), "text");
        appinfo.TermsOfUse = new ApplicationBinaryConfiguration(new MemoryStream(UTF8Encoding.Default.GetBytes(TextBoxTermsofUse.Text)), "text");
        appinfo.ConfigurationOptions = ApplicationOptions.Default;
        return appinfo;
    }


    protected void LinkButtonSignIn_Click(object sender, EventArgs e)
    {
        PatientConnectUtilities healthvaultUitilities = new PatientConnectUtilities(new Guid(ConfigurationManager.AppSettings["ApplicationId"]));
        ApplicationInfo appinfo = CreateApplicationInfo();

        //Calls the Create Application method for generating the Application Id
        Guid newApplicationID = healthvaultUitilities.CreateApplication(appinfo);

        //Create new practice in xml file
        ClinicalDataBaseManager.CreateNewPractice(Path.Combine(Server.MapPath(@"Data"), Constants.PracticeXmlFileName),
            newApplicationID, TextBoxProviderName.Text.Trim(), TextBoxUsername.Text.Trim(), TextBoxPassword.Text.Trim());

        //Generate Directory Structure for newly generated application
        ClinicalDataBaseManager.CreateDataBaseDirectories(Path.Combine(Server.MapPath(@"Data\"),
            "Practice-Dr. " + TextBoxProviderName.Text.Trim()));

        Response.Redirect("Login.aspx", false);
    }

    protected void LinkButtonCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("Login.aspx", false);
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (!(e.Row.Cells[5].Text.Equals(Medication.TypeId.ToString()) ||
                e.Row.Cells[5].Text.Equals(LabTestResults.TypeId.ToString()) ||
                e.Row.Cells[5].Text.Equals(Basic.TypeId.ToString()) ||
                e.Row.Cells[5].Text.Equals(PersonalImage.TypeId.ToString()) ||
                e.Row.Cells[5].Text.Equals(_BasicDemographicTypeId) ||
                e.Row.Cells[5].Text.Equals(_CcdTypeId) ||
                e.Row.Cells[5].Text.Equals(_CcrTypeId)))
            {
                e.Row.Cells[1].Enabled = false;
                e.Row.Cells[2].Enabled = false;
                e.Row.Cells[3].Enabled = false;
                e.Row.Cells[4].Enabled = false;
                e.Row.Cells[5].Enabled = false;
            }
        }
        e.Row.Cells[5].Visible = false;
    }

    /// <summary>
    /// Create authorization table from gird
    /// </summary>
    /// <returns>DataTable</returns>
    private DataTable CreateAuthorizationTable()
    {
        DataTable authTable = new DataTable();
        //Create Column to authentication Table
        authTable.Columns.Add("Item");
        authTable.Columns.Add("Create", typeof(bool));
        authTable.Columns.Add("Read", typeof(bool));
        authTable.Columns.Add("Update", typeof(bool));
        authTable.Columns.Add("Delete", typeof(bool));
        authTable.Columns.Add("TypeId");

        //Fetch controls of enabled row and store the value in authentication table
        for (int iterator = 0; iterator < GridView1.Rows.Count; iterator++)
        {
            object[] parameter = new object[6];
            if (GridView1.Rows[iterator].Cells[1].Enabled)
            {
                parameter[0] = GridView1.Rows[iterator].Cells[0].Text;
                CheckBox checkboxCreate = (CheckBox)GridView1.Rows[iterator].Cells[1].FindControl("Create");
                CheckBox checkboxRead = (CheckBox)GridView1.Rows[iterator].Cells[2].FindControl("Read");
                CheckBox checkboxUpdate = (CheckBox)GridView1.Rows[iterator].Cells[3].FindControl("Update");
                CheckBox checkboxDelete = (CheckBox)GridView1.Rows[iterator].Cells[3].FindControl("Delete");
                parameter[1] = checkboxCreate.Checked;
                parameter[2] = checkboxRead.Checked;
                parameter[3] = checkboxUpdate.Checked;
                parameter[4] = checkboxDelete.Checked;
                parameter[5] = GridView1.Rows[iterator].Cells[5].Text;
                authTable.Rows.Add(parameter);
            }
        }
        return authTable;
    }

}